import request from '../../../utils/request.js'
import login from '../../../utils/login.js'
import qs from '../../../libs/qs.js'
import config from '../../../utils/config.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isReady: false,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      options: options
    })

    this.init()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  async init() {
    await login({
      referrerId: this.data.options.referrerId || ''
    })
    this.getUserInfo()
  },

  getUserInfo() {
    if (app.globalData.userInfo) {
      this.setData({
        hasUserInfo: true
      })
      this.ready()
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      if (!app.globalData.isReady) {
        app.userInfoReadyCallback = res => {
          if (res) {
            this.setData({
              hasUserInfo: true
            })
          }
          this.ready()
        }
      } else {
        this.ready()
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            hasUserInfo: true
          })
          this.ready()
        }
      })
    }
  },

  bindStart() {
    clearTimeout(this.timeout)
    this.next()
  },

  ready() {
    this.setData({
      'isReady': true
    })
    this.timeout = setTimeout(this.next, config.startupTime)
  },

  next() {
    const query = qs.stringify(this.data.options, {
      encode: false
    })
    let url = config.homePath
    if (config.requiredAuth && !this.data.hasUserInfo) {
      url = '/pages/auth/auth'
    }
    wx.reLaunch({
      url: url + '?' + query,
    })
  },

  /**
   * 微信扫码
   */
  wxScan() {
    const options = this.data.options
    if (!options.q || this.data.scaned) {
      return false;
    }
    this.setData({
      'scaned': true
    })
    this.handleScan(decodeURIComponent(options.q))
  },

  handleScan(url) {
    const index = url.indexOf('?')
    if (index >= 0) {
      url = url.substr(index)
    }
    const obj = qs.parse(url, { ignoreQueryPrefix: true })
    if ('1' === obj.t) {
      wx.navigateTo({
        url: '/pages/xuanfang/detail?loupan_id=' + obj.id,
      })
    }
  },
})